package evi.com.evi.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.bean.DisposeOrderBean;
import evi.com.evi.bean.SubOrderDetailBean;
import evi.com.evi.pager.PendingOrderPager;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.MessageDialog;
import evi.com.evi.utils.OrderStatus;
import evi.com.evi.utils.ToastUtils;
import evi.com.evi.view.MyGridView;


/**
 * Created by YX_BOSS on 2017/3/11.
 */

public class PendingOrderAdapter extends RecyclerView.Adapter<PendingOrderAdapter.MyViewHolder> implements Filterable {
    private Context context;
    private List<DisposeOrderBean> jiedanList;
    //用来存储过滤的结果集
    private List<DisposeOrderBean> copyJiedanList;

    public PendingOrderPager pendingOrderPager;

    public void clearResult() {
        if (jiedanList != null) jiedanList.clear();
        if (copyJiedanList != null) copyJiedanList.clear();
    }

    public void addResult(DisposeOrderBean bean) {
        if (jiedanList == null) {
            jiedanList = new ArrayList<DisposeOrderBean>();
        }
        if (copyJiedanList == null) {
            copyJiedanList = new ArrayList<DisposeOrderBean>();
        }
        jiedanList.add(bean);
        copyJiedanList.add(bean);
    }

    public int getResultSize() {
        return (jiedanList != null) ? jiedanList.size() : 0;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_order_time;        //时间
        TextView tv_text_1;            //首三项
        TextView tv_text_2;
        TextView tv_text_2_2;           //手机号
        TextView tv_text_3;

        TextView tv_user;                //收货人
        TextView tv_phone;                //收货人号码
        TextView tv_trans_type;        //配送方式
        TextView tv_peisong_user;        //配送员
        TextView tv_cancle_reason;    //取消订单原因
        TextView tv_refuse_reason;    //拒绝原因
        TextView tv_money;                //订单金额
        TextView tv_detail;            //隐藏详情
        TextView tv_refuse;            //拒绝
        TextView tv_btn_manager;       //按钮

        FrameLayout fl_goods;            //商品表
        MyGridView gv_goods;      //商品表

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_order_time = (TextView) itemView.findViewById(R.id.tv_order_time);
            tv_text_1 = (TextView) itemView.findViewById(R.id.tv_text_1);
            tv_text_2 = (TextView) itemView.findViewById(R.id.tv_text_2);
            tv_text_2_2 = (TextView) itemView.findViewById(R.id.tv_text_2_2);
            tv_text_3 = (TextView) itemView.findViewById(R.id.tv_text_3);
            tv_user = (TextView) itemView.findViewById(R.id.tv_user);
            tv_phone = (TextView) itemView.findViewById(R.id.tv_phone);
            tv_trans_type = (TextView) itemView.findViewById(R.id.tv_trans_type);
            tv_peisong_user = (TextView) itemView.findViewById(R.id.tv_peisong_user);
            tv_cancle_reason = (TextView) itemView.findViewById(R.id.tv_cancle_reason);
            tv_refuse_reason = (TextView) itemView.findViewById(R.id.tv_refuse_reason);
            tv_money = (TextView) itemView.findViewById(R.id.tv_money);
            tv_detail = (TextView) itemView.findViewById(R.id.tv_detail);
            tv_refuse = (TextView) itemView.findViewById(R.id.tv_refuse);
            tv_btn_manager = (TextView) itemView.findViewById(R.id.tv_btn_manager);

            fl_goods = (FrameLayout) itemView.findViewById(R.id.fl_goods);
            gv_goods = (MyGridView) itemView.findViewById(R.id.gv_goods);
        }
    }

    public PendingOrderAdapter(Context context, List<DisposeOrderBean> quHuoBeanList, PendingOrderPager pendingOrderPager) {
        this.context = context;
        this.jiedanList = quHuoBeanList;
        this.copyJiedanList = new ArrayList();
        this.copyJiedanList.addAll(quHuoBeanList);
        this.pendingOrderPager = pendingOrderPager;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_lv_order_dispose, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }


    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        final DisposeOrderBean bean = jiedanList.get(position);
        Log.e("", "bean.OrderNo=" + bean.getOrder() + ", statue=" + bean.getOrderStatus() + ", cancel=" + bean.getOrderCancelStatus());

        if (OrderStatus.MAINORDER_STATUS_WAIT_ACCEPT == bean.getOrderStatus()
                && (bean.getOrderCancelStatus() == null || bean.getOrderCancelStatus() != OrderStatus.MAINORDER_CANCEL_STATUS_APPEAL)) {
            holder.tv_order_time.setText(bean.getOrder_time());
            holder.tv_text_1.setText(bean.getOrder());
            holder.tv_text_2.setText(bean.getState());
            holder.tv_text_3.setText(bean.getTime());
            holder.tv_user.setText(bean.getName());
            holder.tv_phone.setText(bean.getTelnum());
            holder.tv_trans_type.setText(bean.getType());
            holder.tv_money.setText(bean.getMoney());
            holder.tv_btn_manager.setText("确认接单");
            holder.tv_detail.setText("展开详情");

            List<SubOrderDetailBean> foodList = bean.getFoodList();
            GridGoodsAdapter goodsAdapter = new GridGoodsAdapter(context, foodList);
            holder.gv_goods.setAdapter(goodsAdapter);

            holder.tv_user.setVisibility(View.GONE);
            holder.tv_phone.setVisibility(View.GONE);
            holder.tv_trans_type.setVisibility(View.GONE);

            holder.tv_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    phone(bean.getTelnum());
                }
            });

            holder.tv_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("TAG", "onClick:+++++ ");
                    if (holder.tv_detail.getText().toString().equals("展开详情")) {
                        holder.tv_detail.setText("隐藏详情");
                        holder.tv_user.setVisibility(View.VISIBLE);
                        holder.tv_phone.setVisibility(View.VISIBLE);
                        holder.tv_trans_type.setVisibility(View.VISIBLE);
                    } else {
                        holder.tv_detail.setText("展开详情");
                        holder.tv_user.setVisibility(View.GONE);
                        holder.tv_phone.setVisibility(View.GONE);
                        holder.tv_trans_type.setVisibility(View.GONE);
                    }
                }
            });

            String time = bean.getTime();
            time = time.substring(7, 12);
            final String dealTime;
            //服务员送
            if ("送货方式：配送员送".equals(bean.getType())) {
                dealTime = dealTime(time);
            } else {
                dealTime = time;
            }


            Log.e("TAG", "onBindViewHolder: ========" + time);

            holder.tv_refuse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppUtils.showMsgDialog(context, "拒绝理由", "刚售完", "送不过来", 2, new AppUtils.MsgCallBackData() {
                        @Override
                        public void clickMsg(Dialog d, String data) {
                            pendingOrderPager.sendDealOrderRequest(bean.getMainOrderId(), OrderStatus.MAINORDER_STATUS_REJECT, data, position);
//                            ToastUtils.showMsg(context, "" + data);
                            d.dismiss();
                        }
                    });
                }
            });

            holder.tv_btn_manager.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppUtils.showMsgDialog(context, "确认接单吗？", "确认", "取消", 1, dealTime, new AppUtils.MsgCallBack() {
                        @Override
                        public void confirmMsg(MessageDialog d) {
                            pendingOrderPager.sendDealOrderRequest(bean.getMainOrderId(), OrderStatus.MAINORDER_STATUS_ACCEPT, "", position);
//                            ToastUtils.showMsg(context, "接单成功,orderId="+bean.getMainOrderId()+"&newStatus"+OrderStatus.MAINORDER_STATUS_ACCEPT);
                            d.dismiss();
                        }

                        @Override
                        public void cancelMsg(MessageDialog d) {
                            d.dismiss();
                        }
                    });
                }
            });


            holder.tv_cancle_reason.setVisibility(View.GONE);
            holder.tv_peisong_user.setVisibility(View.GONE);
            holder.tv_refuse_reason.setVisibility(View.GONE);
        } else {
            holder.tv_order_time.setText(bean.getOrder_time());
            holder.tv_text_1.setText(bean.getOrder());
            holder.tv_text_2.setText(bean.getState());
            holder.tv_text_3.setText(bean.getTime());
            holder.tv_user.setText(bean.getName());
            holder.tv_phone.setText(bean.getTelnum());
            holder.tv_trans_type.setText(bean.getType());
            holder.tv_cancle_reason.setText(bean.getReason());
            holder.tv_money.setText(bean.getMoney());
            holder.tv_btn_manager.setText("同意");
            holder.tv_detail.setText("展开详情");

            holder.tv_user.setVisibility(View.GONE);
            holder.tv_phone.setVisibility(View.GONE);
            holder.tv_trans_type.setVisibility(View.GONE);
            holder.tv_cancle_reason.setVisibility(View.GONE);

            List<SubOrderDetailBean> foodList = bean.getFoodList();
            GridGoodsAdapter goodsAdapter = new GridGoodsAdapter(context, foodList);
            holder.gv_goods.setAdapter(goodsAdapter);

            holder.tv_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    phone(bean.getTelnum());
                }
            });

            holder.tv_detail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (holder.tv_detail.getText().toString().equals("展开详情")) {
                        holder.tv_detail.setText("隐藏详情");
                        holder.tv_user.setVisibility(View.VISIBLE);
                        holder.tv_phone.setVisibility(View.VISIBLE);
                        holder.tv_trans_type.setVisibility(View.VISIBLE);
                        holder.tv_cancle_reason.setVisibility(View.VISIBLE);
                    } else {
                        holder.tv_detail.setText("展开详情");
                        holder.tv_user.setVisibility(View.GONE);
                        holder.tv_phone.setVisibility(View.GONE);
                        holder.tv_trans_type.setVisibility(View.GONE);
                        holder.tv_cancle_reason.setVisibility(View.GONE);
                    }
                }
            });

            holder.tv_refuse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppUtils.showMsgDialog(context, "拒绝理由", "货已送出，无法取消订单", "商品无质量问题，暂不支持退款", 2, new AppUtils.MsgCallBackData() {
                        @Override
                        public void clickMsg(Dialog d, String data) {
                            pendingOrderPager.sendDealOrderRequest(bean.getMainOrderId(), OrderStatus.MAINORDER_CANCEL_STATUS_REFUSED, data, position);
//                            ToastUtils.showMsg(context, "" + data);
                            d.dismiss();
                        }
                    });
                }
            });

            holder.tv_btn_manager.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppUtils.showMsgDialog(context, "确认退单吗？", "确认", "取消", 1, null, new AppUtils.MsgCallBack() {
                        @Override
                        public void confirmMsg(MessageDialog d) {
                            pendingOrderPager.sendDealOrderRequest(bean.getMainOrderId(), OrderStatus.MAINORDER_CANCEL_STATUS_AGREE, "", position);
//                            ToastUtils.showMsg(context, "退单成功");
                            d.dismiss();
                        }

                        @Override
                        public void cancelMsg(MessageDialog d) {
                            d.dismiss();
                        }
                    });
                }
            });


            holder.tv_refuse_reason.setVisibility(View.GONE);
            holder.tv_peisong_user.setVisibility(View.GONE);

        }


    }

    public String dealTime(String time) {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
        Date date = null;
        try {
            date = sf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        date.setMinutes(date.getMinutes() - 10);
        String dealTime = sf.format(date);
        return dealTime;
    }

    /**
     * 拨打电话
     *
     * @param phone 电话号
     */

    public void phone(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public int getItemCount() {
        return jiedanList != null ? jiedanList.size() : 0;
    }


    @Override
    public Filter getFilter() {
        return new OrderFilter(this, copyJiedanList);
    }

    /**
     * 过滤类，根据输入的电话或者订单号过滤
     */
    private static class OrderFilter extends Filter {

        private final PendingOrderAdapter adapter;

//        private final List<DisposeOrderBean> originalList;
//
//        private final List<DisposeOrderBean> filteredList;

        private OrderFilter(PendingOrderAdapter adapter, List<DisposeOrderBean> originalList) {
            super();
            this.adapter = adapter;
//            this.originalList = new LinkedList<>(originalList);
//            this.filteredList = new ArrayList<>();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
//            filteredList.clear();
            //初始化过滤结果对象
            final FilterResults results = new FilterResults();
            //假如搜索为空的时候，将复制的数据添加到原始数据，用于继续过滤操作
            if (results.values == null) {
                adapter.jiedanList.clear();
                adapter.jiedanList.addAll(adapter.copyJiedanList);
            }
            //关键字为空的时候，搜索结果为复制的结果
            if (constraint.length() == 0) {
//                adapter.jiedanList.addAll(adapter.copyJiedanList);
                results.values = adapter.copyJiedanList;
                results.count = adapter.copyJiedanList.size();
            } else {
                final String filterPattern = constraint.toString().toLowerCase().trim();

                final ArrayList<DisposeOrderBean> newValues = new ArrayList<DisposeOrderBean>();

                for (final DisposeOrderBean user : this.adapter.copyJiedanList) {
                    if (user.getTelnum() != null && user.getTelnum().contains(constraint)) {
                        newValues.add(user);
                    } else if (user.getOrder() != null && user.getOrder().contains(constraint)) {
                        newValues.add(user);
                    }
                }
                results.values = newValues;
                results.count = newValues.size();
                Log.e("EE", "===new Value=" + newValues.size());

            }

            Log.e("EE", "--执行performFilter.constraint=" + constraint + ",copyJiedanList.size=" + this.adapter.copyJiedanList.size() + ",result=" + (((ArrayList<DisposeOrderBean>) results.values).size()));
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            Log.e("EE", "--publishResults.constraint=" + constraint + ",originalList.size=" + this.adapter.copyJiedanList.size() + ",result=" + (((ArrayList<DisposeOrderBean>) results.values).size()));
            adapter.jiedanList.clear();//清除原始数据
            adapter.jiedanList.addAll((ArrayList<DisposeOrderBean>) results.values);//将过滤结果添加到这个对象

            adapter.pendingOrderPager.disposeFalseFragment.getCount(adapter.pendingOrderPager, "" + results.count);

            if (results.count > 0) {

                adapter.notifyDataSetChanged();//有关键字的时候刷新数据
            } else {
                //关键字不为零但是过滤结果为空刷新数据
                if (constraint.length() != 0) {
                    adapter.notifyDataSetChanged();
                    return;
                }
                //加载复制的数据，即为最初的数据
//                adapter.set.setFriends(adapter.copyJiedanList);
                adapter.jiedanList.addAll(adapter.copyJiedanList);
            }
        }
    }

    //使用方法：
    //PendingOrderAdapter.getFilter().filter(text)
}
